package cn.wolfcode.shop.cloud.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

//@Component
public class ErrorResponseJSONFilter extends ZuulFilter {
    public String filterType() {
        return "error";
    }

    public int filterOrder() {
        return 0;
    }

    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return ctx.getThrowable() != null && !ctx.getBoolean("sendErrorFilter.ran", false);
    }

    public Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletResponse response = requestContext.getResponse();
        Map map = new HashMap();
        if(requestContext.get("rateLimitExceeded").equals("true")){
            map.put("code",429);
            map.put("msg","操作过于频繁");
        }else{
            map.put("code",500);
            map.put("msg","系统异常");
        }
        try {
            response.setContentType("text/json;charset=utf8");
            response.getWriter().write(JSON.toJSONString(map));
        } catch (IOException e) {
            e.printStackTrace();
        }
        requestContext.setSendZuulResponse(false);
        return null;
    }
}
